import logging
import re

from waveapi import simplejson as json
from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import robot_abstract
from waveapi import document
from waveapi import ops
from google.appengine.api import urlfetch
import base64

class Command(object):
    def __init__(self, name, pattern, func):
        self.name = name
        self.pattern = pattern
        self.func = func
    def __call__(self, properties, context, user, **kwargs):
        return self.func(properties, context, user, **kwargs)

def mailcheck(properties, context, user, **kwargs):
    logging.debug("Wa hay and off we go")
    url = "http://mailproxy.collaborynth.com.au"
    logging.debug(url)
    username = kwargs.get("USERNAME", None)
    password = kwargs.get("PASSWORD", None)
    payload = "func=get_mail"
    payload += "&user="+username
    payload += "&password="+password 
    logging.debug(payload)
    res = urlfetch.fetch(url=url, payload=payload, method=urlfetch.POST, deadline=10)
    logging.debug(res.status_code)
    if res.status_code == 200:
        #logging.debug(res.content)
        mail_list = json.loads(res.content)
        for mail in mail_list:
            try:
                title = mail['subject']
                logging.debug(title)
                root_wavelet = context.GetRootWavelet()
                rep_wave = robot_abstract.NewWave(context, root_wavelet.GetParticipants())
                rep_wavelet = rep_wave.CreateBlip()
                rep_wavelet.GetDocument().SetText(title)
            except:
                pass

def OnRobotAdded(properties, context):
    """Holding text"""
    
    
def onButtonClick(properties, context):
    """Holding text"""
    
def onBlipSubmitted(properties, context):
    """Holding text"""
    logging.debug("Blip Submitted")
    blip = context.GetBlipById(properties['blipId'])
    user = blip.GetCreator()
    words = blip.GetDocument().GetText()
    commands = []
    commands.append(Command("get_mail", 
                            r"^get_mail ?(?P<USERNAME>[\w\d]+)? ?(?P<PASSWORD>[\w\d]+)?$",
                             mailcheck))
    
    for command in commands:
        pat = re.compile(command.pattern)
        m = pat.search(words)
        if m:
            logging.debug("groupdict: %s" % str(m.groupdict()))
            command(properties, context, user, **m.groupdict())
            return  
    return

if __name__ == '__main__':
    myRobot = robot.Robot('collabmailbot', 
      image_url='http://collabmailbot.appspot.com/icon.png',
      version='1',
      profile_url='http://collabmailbot.appspot.com/')
    myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
    myRobot.RegisterHandler(events.BLIP_SUBMITTED, onBlipSubmitted)
    myRobot.RegisterHandler(events.FORM_BUTTON_CLICKED, onButtonClick)
    myRobot.Run()